package com.fakeofarty;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

import org.xmlpull.v1.XmlSerializer;

import android.location.Location;
import android.os.Environment;
import android.text.format.Time;
import android.util.Xml;

public class KMLCreator {

	static final public String TYPE_START = "start";
	static final public String TYPE_STOP = "stop";
	static final public String TYPE_CHECKPOINT = "checkpoint";
	static final public String TYPE_BACKPOINT = "backpoint";
	static final public String TYPE_TRACK = "track";

	XmlSerializer mSerializer = Xml.newSerializer();
	FileWriter mWriter;
	boolean mCanWrite = true;

	public void create() {
		try {
			mCanWrite = true;
			Time current_time = new Time();
			current_time.setToNow();
			(new File(Environment
					.getExternalStorageDirectory().getAbsolutePath() +  "/Ftrip/")).mkdirs();
			mWriter = new FileWriter(new File(Environment
					.getExternalStorageDirectory().getAbsolutePath() +  "/Ftrip/", current_time.format("%Y-%m-%d-%H-%M")
					+ ".kml"));
			mSerializer.setOutput(mWriter);
			mSerializer.startDocument("UTF-8", true);
			mSerializer.startTag("", "kml");
			mSerializer.attribute("", "xmlns",
					"http://earth.google.com/kml/2.0");
			mSerializer.attribute("", "xmlns:atom",
					"http://www.w3.org/2005/Atom");
			mSerializer.startTag("", "Document");

			mSerializer.startTag("", "atom:author").startTag("", "atom:name");
			mSerializer.text("FTrip");
			mSerializer.endTag("", "atom:name").endTag("", "atom:author");

			mSerializer.startTag("", "name");
			mSerializer.cdsect(current_time.format("%Y-%m-%d-%H-%M"));
			mSerializer.endTag("", "name");

			mSerializer.startTag("", "Style").attribute("", "id", TYPE_TRACK)
					.startTag("", "LineStyle");
			mSerializer.startTag("", "color").text("7f0000ff")
					.endTag("", "color");
			mSerializer.startTag("", "width").text("4").endTag("", "width");
			mSerializer.endTag("", "LineStyle").endTag("", "Style");

			addIcon(TYPE_START,
					"http://www.google.com/mapfiles/kml/paddle/go.png", "1");
			addIcon(TYPE_STOP,
					"http://www.google.com/mapfiles/kml/paddle/stop.png", "1");
			addIcon(TYPE_CHECKPOINT,
					"http://www.google.com/mapfiles/kml/paddle/flag.png", "1");
			addIcon(TYPE_BACKPOINT,
					"http://www.google.com/mapfiles/kml/paddle/recycle.png",
					"1");

		} catch (IOException ioe) {
			mCanWrite = false;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public void writePath(ArrayList<WayPoint> pointArray) {
		if (!mCanWrite)
			return;
		try {
			addPath(pointArray);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public void writeCheckpoints(ArrayList<WayPoint> pointArray) {
		if (!mCanWrite)
			return;
		try {
			for (WayPoint point : pointArray) {
				addPoint(point, TYPE_CHECKPOINT);
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public void writeBackPoints(ArrayList<WayPoint> pointArray) {
		if (!mCanWrite)
			return;
		try {
			for (WayPoint point : pointArray) {
				addPoint(point, TYPE_BACKPOINT);
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public void saveXML() {
		if (!mCanWrite)
			return;
		try {
			mSerializer.endTag("", "Document");
			mSerializer.endTag("", "kml");
			mSerializer.endDocument();
			mWriter.flush();
			mWriter.close();
			mCanWrite = false;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	void addIcon(String id, String link, String scale) throws IOException,
			IllegalArgumentException, IllegalStateException {
		mSerializer.startTag("", "Style").attribute("", "id", id)
				.startTag("", "IconStyle");
		mSerializer.startTag("", "scale").text(scale).endTag("", "scale");
		mSerializer.startTag("", "Icon").startTag("", "href").text(link)
				.endTag("", "href").endTag("", "Icon");

		mSerializer.startTag("", "hotSpot").attribute("", "x", "32")
				.attribute("", "y", "1").attribute("", "xunits", "pixels")
				.attribute("", "yunits", "pixels").endTag("", "hotSpot");
		mSerializer.endTag("", "IconStyle").endTag("", "Style");
	}

	void addPoint(WayPoint wayPoint, String style) throws IOException,
			IllegalArgumentException, IllegalStateException {
		mSerializer.startTag("", "Placemark");
		mSerializer.startTag("", "description").cdsect(
				Integer.toString(wayPoint.mId) + " ");// Time
		mSerializer.endTag("", "description");
		mSerializer.startTag("", "styleUrl").text("#" + style)
				.endTag("", "styleUrl");
		mSerializer.startTag("", "Point").startTag("", "coordinates")
				.text(getPointCoordinates(wayPoint)).endTag("", "coordinates")
				.endTag("", "Point");
		mSerializer.endTag("", "Placemark");
	}

	void addPath(ArrayList<WayPoint> pointArray) throws IOException,
			IllegalArgumentException, IllegalStateException {

		mSerializer.startTag("", "Placemark");
		mSerializer.startTag("", "description").cdsect("path");// Time
		mSerializer.endTag("", "description");
		mSerializer.startTag("", "styleUrl").text("#" + TYPE_TRACK)
				.endTag("", "styleUrl");
		mSerializer.startTag("", "MultiGeometry").startTag("", "LineString")
				.startTag("", "coordinates");
		mSerializer.text(getPointsArray(pointArray));
		mSerializer.endTag("", "coordinates").endTag("", "LineString")
				.endTag("", "MultiGeometry");
		mSerializer.endTag("", "Placemark");
	}

	String getPointsArray(ArrayList<WayPoint> pointArray) {
		String result = "";
		for (WayPoint point : pointArray) {
			result += getPointCoordinates(point) + " ";
		}
		return result;
	}

	String getPointCoordinates(WayPoint wayPoint) {
		return Location.convert(wayPoint.mLongitude, Location.FORMAT_DEGREES)
				+ ","
				+ Location.convert(wayPoint.mLatitude, Location.FORMAT_DEGREES)
				+ ",0";
	}

}
